import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

public class Main {

	private static HttpClient client = new DefaultHttpClient();
	private static HttpGet get = null;
	private static HttpPost post = null;
	private static ResponseHandler<String> responseHandler = null;
	private static List<NameValuePair> nvp = null;
	private static String submit_url = null;

	public static void main(final String[] args) throws Exception {
		pre_login();
		login();
		taojinbi();
	}

	private static void taojinbi() throws Exception {
		get = new HttpGet("http://i.m.taobao.com/coin/take_coin.htm");
		final String view_source = client.execute(get, responseHandler);
		System.out.println(view_source);
		final Document document = Jsoup.parse(view_source);
		final Element ele = document.getElementsByClass("quick").get(0);

		get = new HttpGet(ele.child(0).attr("href"));
		System.out.println(client.execute(get, responseHandler));
	}

	/**
	 * 登录(假设一定登录成功)
	 * 
	 * @throws Exception
	 */
	private static void login() throws Exception {
		post = new HttpPost(submit_url);
		post.setHeader(
				"User-Agent",
				"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.63 Safari/534.3");
		post.setEntity(new UrlEncodedFormEntity(nvp, HTTP.UTF_8));
		System.out.println(client.execute(post));
		post.abort();
	}

	/**
	 * 登录前操作（获取登录表单信息）
	 * 
	 * @throws Exception
	 */
	private static void pre_login() throws Exception {
		get = new HttpGet("http://login.m.taobao.com/login.htm");
		responseHandler = new BasicResponseHandler();
		final String view_source = client.execute(get, responseHandler);
		final Document document = Jsoup.parse(view_source);
		final Element ele = document.getElementsByTag("form").get(0);

		submit_url = ele.attr("action");

		nvp = new ArrayList<NameValuePair>();
		for (final Element e : ele.getElementsByTag("input")) {
			String k, v;
			k = e.attr("name");
			v = e.attr("value");
			if ("TPL_username".equals(k)) {
				nvp.add(new BasicNameValuePair(k, "ping_qc"));
			} else if ("TPL_password".equals(k)) {
				nvp.add(new BasicNameValuePair(k, "ZXCVB!@#$%12345"));
			} else if ("登录".equals(v)) {
				//
			} else {
				nvp.add(new BasicNameValuePair(k, v));
			}
		}
	}
}
